package com.rtf.framework.dao.rule.levelpath;

import com.rtf.framework.common.exception.AppException;
import com.rtf.framework.common.support.dao.handler.AppBaseDataHandlerAdaptor;
import org.springframework.beans.factory.annotation.Autowired;

import javax.persistence.Table;
import java.util.Collection;

public class ParentIdHandler extends AppBaseDataHandlerAdaptor {

    @Autowired
    private LevelPathRecordDao levelPathRecordDao;

    @Override
    public boolean support(Class<?> entityClass) {
        return ParentIdRecord.class.isAssignableFrom(entityClass);
    }

    @Override
    public <T> T preSaveHandler(T entity) {
        ParentIdRecord parentIdRecord = (ParentIdRecord) entity;

        if (parentIdRecord.getParentId() == null) {
            //对于空的父节点记录，默认为0
            parentIdRecord.setParentId(0L);
        }

        return entity;
    }

    @Override
    public <T> T preUpdateHandler(T entity, Collection<String> updateFields) {
        ParentIdRecord parentIdRecord = (ParentIdRecord) entity;
        if (parentIdRecord.getParentId() == null) {
            //对于空的父节点记录，默认为0
            parentIdRecord.setParentId(0L);
        }
        return super.preUpdateHandler(entity, updateFields);
    }

    @Override
    public <ID> void preDeleteHandler(ID id, Class<?> domainClass) {
        Table tableAnno = domainClass.getAnnotation(Table.class);
        if (tableAnno == null) {
            throw new AppException("当前类必须是jpa管理的类");
        }
        int subItemNum = levelPathRecordDao.subNumByParent(tableAnno.name(), id.toString());
        if (subItemNum > 0) {
            throw new AppException("存在关联下级，不能删除。");
        }
        super.preDeleteHandler(id, domainClass);
    }
}
